const COLUMNS = [{
		prop: "name",
		label: "考试名称",
		width: "80"
	},
	{
		prop: "type",
		label: "考试类别",
		width: "160"
	},

	{
		prop: "totalNumber",
		label: "题目数量",
		width: "80"
	},
	{
		prop: "endTime",
		label: "考试截止日期",
		width: "130"
	},
	{
		prop: "totalScore",
		label: "考试总分",
		width: "130"
	},
	{
		prop: "examineNumber",
		label: "考试人数",
		width: "80"
	},
	{
		prop: "passNumber",
		label: "通过人数",
		width: "80"
	},
	{
		prop: "passMark",
		label: "及格线",
		width: "130"
	},
	{
		prop: "testTotalTimes",
		label: "考试次数",
		width: "130"
	},
	{
		prop: "state",
		label: "状态",
		width: "130"
	},
	{
		prop: "addTime",
		label: "添加时间",
		width: "120"
	},
	{
		prop: "updateTime",
		label: "更新时间",
		width: "120"
	}
];
const PCOLUMNS = [{
		prop: "username",
		label: "姓名",
		width: "40"
	}

];

const isNum = (rule, value, callback) => {
		const total = /^[0-9]*$/
		if (!total.test(value)) {
			callback(new Error('输入只能为数字'))
		} else {
			callback()
		}
};
		const dialogrules = {
			endTime: [{
				required: true,
				message: '请输入截止日期',
				trigger: 'blur'
			}],

			name: [{
				required: true,
				message: '请输入考试名称',
				trigger: 'blur'
			}],
			duoxuan: [{
					required: true,
					message: '请输入多选数量',
					trigger: 'change'
				},
				{
					validator: isNum,
					trigger: 'blur'
				}
			],
			danxuan: [{
					required: true,
					message: '请输入单选数量',
					trigger: 'blur'
				},
				{
					validator: isNum,
					trigger: 'blur'
				}
			],
			totalNumber: [{
					required: true,
					message: '请输入题目数量',
					trigger: 'blur'
				},
				{
					validator: isNum,
					trigger: 'blur'
				}
			],
			totalScore: [{
				required: true,
				message: '请输入题目总分',
				trigger: 'blur'
			}],
			examineNumber: [{
				required: true,
				message: '请点击确认选择来选择考试人员',
				trigger: 'blur'
			}],
			type: [{
				required: true,
				message: '请选择考试类别',
				trigger: 'blur'
			}],
			passNumber: [{
				required: true,
				message: '请输入通过人数',
				trigger: 'blur'
			}],
			passMark: [{
				required: true,
				message: '请输入及格线',
				trigger: 'blur'
			}],
			testTotalTimes: [{
				required: true,
				message: '请输入考试总次数',
				trigger: 'blur'
			}],
			state: [{
				required: true,
				message: '请输入状态',
				trigger: 'blur'
			}]
		}

		let app = new Vue({
			el: "#app",
			// router: router,
			data() {
				return {
					combinationForm: {
						defaultProps: {
							children: 'children',
							label: 'label'
						},

					},
					data: [{
						label: '一级 1',
						children: [{
							label: '二级 1-1',
							children: [{
								label: '三级 1-1-1'
							}]
						}]
					}, {
						label: '一级 2',
						children: [{
							label: '二级 2-1',
							children: [{
								label: '三级 2-1-1'
							}]
						}, {
							label: '二级 2-2',
							children: [{
								label: '三级 2-2-1'
							}]
						}]
					}, {
						label: '一级 3',
						children: [{
							label: '二级 3-1',
							children: [{
								label: '三级 3-1-1'
							}]
						}, {
							label: '二级 3-2',
							children: [{
								label: '三级 3-2-1'
							}]
						}]
					}],
					count: 1,
					queryPersonForm: {
						ids: [],
						username: "",
						isactive: "是",
						sex: "",
						address: "",
						phone: "",
						deptid: 0,
						persontype: [],
						pageNo: 1, // 当前页码
						pagesize: 100, // 每页记录数
					},
					activeName: 'first',
					typeoptions: [],
					smalltypeoptions: [],
					stateoptions: STATETYPE,
					teamLink: "i am copy",
					leftbar_show: true,
					// 添加、编辑标识
					action: "",
					tableHeight: window.innerHeight - 180,

					tablecolums: COLUMNS,
					ptablecolums: PCOLUMNS,
					submitDisable: false,
					dialogFormVisible: false,
					testpaperForm: {
						pName: [],
						name: "",
						type: [],
						stype: [],
						totalNumber: "",
						endTime: "",
						totalScore: "",
						examineNumber: "",
						passNumber: "",
						passMark: "",
						testTotalTimes: "",
						state: "待开始",
					},
					queryForm: {
						state: "",
						name: "",
						type: [],
						stype: [],
						addTime: [],
						updateTime: [],
						pageNo: 1, // 当前页码
						pagesize: 100, // 每页记录数
						pagesizes: [10, 20, 50, 100]
					},
					pagepersontotal: 0,
					pagepersontotaltemp: 0,
					pagetotal: 0,
					pagetotaltemp: 0,
					pickerOptions: {
						shortcuts: [{
							text: '最近一周',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
								picker.$emit('pick', [start, end]);
							}
						}, {
							text: '最近一个月',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
								picker.$emit('pick', [start, end]);
							}
						}, {
							text: '最近三个月',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
								picker.$emit('pick', [start, end]);
							}
						}]
					},



					// 多选
					multipleSelection: [],
					pagedatatemp: [], // 当前页结果集
					pagedata: [], // 当前页结果集
					pagepersondatatemp: [], // 当前页用户结果集
					pagepersondata: [], // 当前页用户结果集
					loaded: false,
				}
			},
			methods: {
				getscore() {
					this.testpaperForm.totalNumber = parseInt(this.testpaperForm.danxuan) + parseInt(this.testpaperForm.duoxuan)
					this.testpaperForm.totalScore = parseInt(this.testpaperForm.totalNumber) * 5
				},
				choosePerson() {
					if (this.multipleSelection.length == 0) {
						this.$message.error('请选择考试人员！');
						return;
					}
					this.testpaperForm.pName = [];
					this.testpaperForm.examineNumber = this.multipleSelection.length
					for (let row of this.multipleSelection) {
						this.testpaperForm.pName.push(row.username)
					}				
					//this.$message.success('选择考试人员成功！')
				},
				// 取得组织结构
				async getCombination() {
					// 显示加载框
					const loading = this.$loading(LOAD_STYLE);
					try {
						let res = await axios.get('api/detp/combination');
						if (res.code === 200) {
							this.combinationForm.data = res.data;
						} else {
							this.$message.error(res.message);
						}
					} catch (e) {
						this.$message.error('组织结构请求出错！', e.message);
					}

					// 关闭加载框
					loading.close();
				},
				handleCheckChange(data, checked) {
					this.queryPersonForm.ids = []
					for (i in checked.checkedNodes) {
						this.queryPersonForm.ids.push(checked.checkedNodes[i].id)
					}
					// if(checked==false){
					// 	this.queryPersonForm.ids.splice(this.ids.indexOf(data.id), 1)
					// }else if(checked==true){
					// 	this.queryPersonForm.ids.push(data.id)
					// }
					console.log(this.queryPersonForm.ids)
					this.queryPersonForm.deptid = data.id;
					this.queryPersonForm.persontype = []
					for (i in checked.checkedNodes) {
						this.queryPersonForm.persontype.push(checked.checkedNodes[i].type)
					}
					console.log(this.queryPersonForm.persontype)
					//this.queryPersonForm.type = data.type;
					this.queryPersonForm.pageNo = 1;
					this.queryPerson();
				},
				handleNodeClick(data) {
					// console.log(data);
					// this.queryPersonForm.deptid = data.id;
					// this.queryPersonForm.type = data.type;
					// this.queryPersonForm.pageNo = 1;
					// this.queryPerson();
				},


				// 查询
				async queryPerson() {
					// 显示加载框
					const loading = this.$loading(LOAD_STYLE);
					try {
						let res = await axios.post('api/deptuser/query', this.queryPersonForm);
						if (res.code === 200) {

							this.pagepersondata = res.data;
							this.pagepersontotal = res.total;
						} else {
							this.$message.error(res.message);
						}
					} catch (e) {
						this.$message.error('请求出错！', e.message);
					}
					console.log(this.pagepersontotal)
					// 关闭加载框
					loading.close();
				},
				toolAction(acName) {
					if (acName == "添加") {
						this.add()
					} else if (acName == "选择确认") {
						this.choosePerson()
					}
				},
				add() {
					this.dialogFormVisible = true;
					this.testpaperForm = {
						danxuan: "",
						duoxuan: "",
						name: "",
						type: [],
						stype: [],
						totalNumber: "",
						endTime: "",
						totalScore: "",
						examineNumber: "",
						passNumber: "0",
						passMark: "",
						testTotalTimes: "",
						state: "",
						action: "add",
					}
				},

				// 显示侧边栏
				showLeftBar() {

					if (this.leftbar_show)
						return this.leftbar_show = false
					if (!this.leftbar_show)
						return this.leftbar_show = true

				},
				// 表格多选 
				handleSelectionChange(val) {
					this.multipleSelection = val;
				},
				handleRemove(file, filelist) {},

				handleAvatarSuccess(res, file, filelist) {},



				// 检查数据是否有修改
				checkDataChanged() {
					// 比对数据有无发生变化
					for (let key in this.testpaperForm) {
						if (this.testpaperForm[key] != this.testpaperFormOrg[key]) {
							return true;
						}
					}
					return false;
				},

				start() {
					this.queryForm.pageNo = 1
					this.query()
				},

				// 查询
				async query() {
					this.submitDisable = true;
					// 显示加载框
					const loading = this.$loading(LOAD_STYLE);
					try {
						let res = await axios.post('api/test/querylist', this.queryForm);
						if (res.code === 200) {
							this.pagedata = res.data;
							this.pagetotal = res.total;
							console.log(this.pagedata)
							// for (let item in this.pagedata) {
							// 	this.pagedata[item].add_time = this.pagedata[item].add_time
							// }
							this.$message.success(res.message);

						} else {
							this.$message.error(res.message);
						}
					} catch (e) {
						this.$message.error('请求出错！', e.message);
					}

					// 关闭加载框
					loading.close();
					this.submitDisable = false;
				},
				//修改
				async confirm() {	
					this.testpaperForm.pName=[]
					this.choosePerson()
					console.log(this.testpaperForm.pName)
					if(this.testpaperForm.pName.length==0){
						this.submitDisable = false;
						return;
					}
					this.$refs.testpaperForm.validate(async valid => {
						if (valid) {
							const loading = this.$loading(LOAD_STYLE);		
		
							try {
								let res = null;
								if (this.testpaperForm.action == "add") {
									//添加
									res = await axios.put('api/test/add', this.testpaperForm);
								}
								// else {
								// 	//编辑
								// 	res = await axios.put('api/test/edit', this.testpaperForm);
								// }

								if (res.code === 200) {
									this.query();
									this.dialogFormVisible = false
								} else {
									this.$message.error(res.message);
								}

							} catch (e) {
								this.$message.error('请求出错！', e.message);
							}
							// 关闭加载框
							loading.close();
						}else {
					if (this.testpaperForm.pName.length==0) {
						this.$message.error('请在人员选择中选择人员');
						this.activeName = 'second'
					}else {
						this.$message.error('请确认试卷础信息*号项目都以填写。');
						this.activeName = 'first'
					}
				}
					})
					this.submitDisable = false;
				},



				selectionChange(selection) {
					this.selection = selection
				},
				//开始考试
				startexam(index, row) {
					this.$confirm('此操作将开放本次考试, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						this.testpaperForm = deepCopy(row)
						this.testpaperForm.testId = row.id
						this.starttestpaper()

					}).catch(() => {
						this.$message({
							type: 'info',
							message: '已取消'
						});
					});
				},
				//删除
				remove(index, row) {
					this.$confirm('此操作将永久删除该考试信息, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						this.testpaperForm = deepCopy(row)
						this.testpaperForm.testId = row.id
						this.removetestpaper()

					}).catch(() => {
						this.$message({
							type: 'info',
							message: '已取消删除'
						});
					});
				},

				// // 编辑
				// edit(index, row) {
				// 	this.action = "edit"
				// 	this.index = index;
				// 	console.log(this.pagedata)
				// 	this.dialogFormVisible = true;
				// 	this.testpaperForm = deepCopy(row)
				// 	this.testpaperForm.testId = row.id
				// 	// 保留原始数据，方便比对
				// 	this.testpaperFormOrg = deepCopy(row)
				// },
				//删除
				async removetestpaper() {
					try {
						let res = await axios.post('api/test/remove', this.testpaperForm);
						console.log(res)
						if (res.code === 200) {
							this.query();
							this.$message({
								type: 'success',
								message: '删除成功!'
							});
						} else {
							this.$message.error(res.message);
						}

					} catch (e) {
						this.$message.error('请求出错！', e.message);
					}

				},

				async starttestpaper() {
					try {
						let res = await axios.put('api/test/start', this.testpaperForm);
						console.log(res)
						if (res.code === 200) {
							this.query();
							this.$message({
								type: 'success',
								message: '考试开始!'
							});
						} else {
							this.$message.error(res.message);
						}

					} catch (e) {
						this.$message.error('请求出错！', e.message);
					}
				},

				// 设定表格当前页
				handleCurrentPageChange(selectedPageNo) {
					this.queryForm.pageNo = selectedPageNo
					// 加载数据页
					this.query()
				},
						//设定每页记录数
				handleSizeChange(val) {
					this.queryForm.pagesize = val
				  // 加载数据页
				  this.query()
				},

				handleClick(tab, event) {
					console.log(tab, event);
				},

				createStateFilter(queryString) {
					return (state) => {
						return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
					};
				},
				handleSelect(item) {
					console.log(item);
				},
				async initTestTypes() {
					try {
						let res = await axios.get('api/test/inittype');
						if (res.code === 200) {
							this.typeoptions = res.data
						} else {
							this.$toast("题库大分类取得出错。");
						}
					} catch (e) {
						this.$toast("网络连接异常。");
					}
				},
				async initTestSubTypes(type) {
					try {
						let res = await axios.get('api/test/initsubtype/' + type);
						if (res.code === 200) {
							this.smalltypeoptions = res.data
						} else {
							this.$toast("题库小分类取得出错。");
						}
					} catch (e) {
						this.$toast("网络连接异常。");
					}
				},
				changeType(value) {
					this.initTestSubTypes(value);
				}
			},

			async mounted() {
				// 自动调整表格高度
				window.onresize = () => {
						return (() => {
							this.tableHeight = window.innerHeight - 180
						})()
					},
					//初始组织结构
					this.getCombination()

				this.initTestTypes();
				this.initTestSubTypes("None");

			}

		});
